﻿using Microsoft.AspNetCore.Mvc;
using WebAPI.Dao;
using WebAPI.Entities;
using WebAPI.Entities.Dto;
using WebAPI.Services;

namespace WebAPI.Controllers;

[ApiController]
[Route("api/[controller]/[Action]")]
public class ArticleController : ControllerBase
{
    private ArticleService _articleService = new ArticleService();
    
    [HttpPost(Name = "PublishArticle")]
    public string PublishArticle(ArticleDto articleDto)
    {
        Article article = new Article();
        article.UserId = articleDto.UserId;
        article.Title = articleDto.Title;
        article.InnerText = articleDto.InnerText;
        article.Tag = articleDto.Tag;
        article.Star = articleDto.Star;
        article.Watcher = articleDto.Watcher;
        bool flag = _articleService.PublicArticle(article);
        if (!flag)
        {
            return ResultData.Fail("发布文章失败，请稍后重试");
        }
        return ResultData.Ok("发布成功");
    }
    
    [HttpGet(Name = "GetArticle")]
    public string GetArticle(string id)
    {
        Article article = _articleService.GetOneArticles(id);
        if (article == null)
        {
            return ResultData.Fail("删除文章失败，请稍后重试");
        }
        return ResultData.Ok(article);
    }
    
    [HttpGet(Name = "GetUserArticle")]
    public string GetUserArticle(string userId)
    {
        List<Article> articles = _articleService.GetAllArticles(userId);
        if (articles == null)
        {
            return ResultData.Fail("获取文章失败，请稍后重试");
        }
        return ResultData.Ok(articles);
    }
    
    [HttpGet(Name = "GetArticles")]
    public string GetArticles()
    {
        List<Article> articles = _articleService.GetAllArticles();
        if (articles.Count == 0)
        {
            return ResultData.Fail("获取文章失败，请稍后重试");
        }
        return ResultData.Ok(articles);
    }
    
    [HttpPut(Name = "DeleteArticle")]
    public string DeleteArticle(Article article)
    {
        bool flag = _articleService.DeleteArticle(article);
        if (!flag)
        {
            return ResultData.Fail("删除文章失败，请稍后重试");
        }
        return ResultData.Ok("删除成功");
    }
    
    [HttpPut(Name = "UpdateArticle")]
    public string UpdateArticle(Article article)
    {
        bool flag = _articleService.UpdateArticle(article);
        if (!flag)
        {
            return ResultData.Fail("更新文章失败，请稍后重试");
        }
        return ResultData.Ok("更新文章成功");
    }
}